#include "version.h"

#include <stdio.h>
#include <stdlib.h>
#ifdef __linux__
#include <memory>
#endif // __linux__

#include "appexitio.h"
#include "lib_acl.h"
#include "Log.h"
#include "IOToAliyun.h"
#include "business_def.h"
#include "acl_cpp/lib_acl.hpp"
#include "master_service.h"

namespace GlobalVar {
	std::string m_app_conf_file = "appconf.xml";
	bool exitFlag = false;
	extern std::string logname;
};

#ifdef WIN32
//server conf
char SVCNAME[128] = "pyfreeMgr";
char SVCDESC[256] =
"\r\n pyfree Technology Ltd \r\n "
"https://gitee.com/pyzxjfree/pyfree-IotEdge \r\n "
"email:py8105@163.com \r\n "
"pyfree-sysmgr system service \r\n "
"Service installation success";
#endif // WIN32
//linux服务名依赖于安装脚本配置,详情参考demo下的脚本
#ifdef WIN32
int MyMain(int argc, char* argv[])
#else
int main(int argc, char *argv[])
#endif
{
	#ifdef WIN32
	GlobalVar::logname = std::string(SVCNAME);
	#else
	GlobalVar::logname = "pyfreeMgr";	//最好与安装脚本保持一致,采用服务名
	#endif
	if (!pyfree::LicenseCheck())
	{
		Print_WARN("license is error, please make sure software instance is right first!");
		exit(true);
	}
	pyfree::versionLog();
	pyfree::checkArg(argc,argv);
	BusinessDef* ptr_BD = BusinessDef::getInstance();
	std::auto_ptr<IOToMqttAliyun> ptr_io_aliyun(NULL);
	if(ptr_BD->getAliyunFunc())
	{
		//阿里云接口
		Print_NOTICE("log aliyun iot interface init start!\n");
		ptr_io_aliyun.reset(new IOToMqttAliyun());
		ptr_io_aliyun->start(true);
		CLogger::createInstance()->Log(MsgInfo, "the thread for aliyun iot is init and start!");
	}else{
		CLogger::createInstance()->Log(MsgInfo, "the thread for aliyun iot is off!");
	}
	//
#ifdef WIN32
	if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)ctrlhandler, true))
	{
		CLogger::createInstance()->Log(MsgWarn, "install signal handler error!");
	}
#else
	SignalHandler * g_exit_handler = NULL;
	g_exit_handler = new SignalHandler();
	if(!g_exit_handler){
		CLogger::createInstance()->Log(MsgWarn, "install signal handler error!");
	}
#endif // WIN32
	if(ptr_BD->getwebfunc())
	{
		//http_servlet test
		// 初始化 acl 库
		acl::acl_cpp_init();

		master_service& ms = acl::singleton2<master_service>::get_instance();

		// 设置配置参数表
		ms.set_cfg_int(var_conf_int_tab);
		ms.set_cfg_int64(var_conf_int64_tab);
		ms.set_cfg_str(var_conf_str_tab);
		ms.set_cfg_bool(var_conf_bool_tab);

		// acl::log::stdout_open(true);  // 日志输出至标准输出
		char addr[128] = {0};
		sprintf(addr,"%s:%d",ptr_BD->getWebIp().c_str(),ptr_BD->getWebPort());
		// const char* addr = "192.168.174.130:8888";
		Print_NOTICE("listen on: %s\r\n", addr);
		CLogger::createInstance()->Log(MsgInfo, "the service for web config is init and start!");
		ms.run_alone(addr, NULL, 5);  // 单独运行方式
	}else{
		CLogger::createInstance()->Log(MsgInfo, "the service for web config is off!");
		while (!GlobalVar::exitFlag)
		{
			sleep(10);
		}
	}
	return 0;
}
